<template>
  <el-dialog title="即时测验" :close-on-click-modal="false" :destroy-on-close="true" width="600px" :visible.sync="isShow" :before-close="closeBox">
    <div class="time">耗时：{{timing}}</div>
    <div class="question-title" v-if="topic.subject_content" v-html="'【'+ topic.sort_index + '】' + topic.subject_content"></div>
    <!-- 图片 -->
    <div class="media-box" v-if="topic.display_type === '2'">
      <img :src="topic.file_url" style="width:100%">
    </div>
    <!-- 音频 -->
    <div class="media-box" v-if="topic.display_type === '3'">
      <audio class="audio" controls :src="topic.file_url" controlsList="nodownload"></audio>
    </div>
    <!-- 视频 -->
    <div class="media-box" v-if="topic.display_type === '4'">
      <video class="video" controls :src="topic.file_url">
      </video>
    </div>
    <div v-for="(item, i) in topic.options" :key="i">
      <div class="item cursor" v-if="topic.subject_type!=='14'&&topic.subject_type!=='17'" :class="{ active: sheet[currentTopicIndex].stu_answer === item.num || item.checked}" @click="choiceSheet(item)">
        <span class="chooseBtn cursor" >{{item.num}}</span>
        <span class="question-content" v-if="topic.subject_type==='13'" >
                  <input type="text" v-model="item.stu_answer" @blur="inputSheet(topic.options)">
                </span>
        <span class="question-content" v-if="topic.subject_type==='10'">
                  {{ item.stu_answer }}
                </span>
        <span class="question-content" v-if="topic.subject_type==='11'">
                  {{ item.stu_answer }}
                </span>
        <span class="question-content" v-if="topic.subject_type==='12'">
                  {{ item.stu_answer }}
                </span>
      </div>
      <div class="item cursor" v-else>
        <textarea :rows="topic.subject_type==='14'?4:10" v-model="item.stu_answer"></textarea>
      </div>
    </div>
    <!-- 底部按钮 -->
    <div class="controller">
      <div style="width: 100%;">
        <el-button :disabled="currentTopicIndex === 0" @click="jumpPage(-1)">上一题</el-button>
        <el-button :disabled="currentTopicIndex === subjectList.length - 1" @click="jumpPage(1)" >下一题</el-button>
        <el-button :disabled="btnDisabled" type="primary" @click="submitForm" class="fr">提交</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { testMain, updateTestDuration, testSubmit } from '@/api/student/lesson/classroom'
export default {
  props: ['id'],
  data () {
    return {
      isShow: true,
      btnDisabled: false,
      timing: '00:00',
      info: {
        isEnd: '',
        isLimited: '',
        isTestReport: '',
        limitedEndTime: '',
        limitedStartTime: '',
        stuOnlineLessonTestId: '',
        testTitle: '',
        subjectList: []
      },
      topic: {
        file_url: '',
        display_type: '',
        sort_index: '', // 第几题
        subject_id: '', // 题目id
        subject_content: '', // 题目内容
        subject_type: 10, // 题目类型
        itemList: [], // 选项
        options: [] // 题目配置项
      },
      subjectList: [],
      sheet: [], // 答题卡
      // 当前题目的索引
      currentTopicIndex: 0
    }
  },
  methods: {
    async testMain () {
      const res = await testMain({ activityId: this.id })
      if (res.code === '200') {
        console.log(res.data)
        this.info = res.data
        this.subjectList = this.info.subjectList
        this.sheet = this.info.subjectList.map(item => {
          return {
            subject_id: item.subject_id, // 题目id
            subject_type: item.subject_type, // 题目类型
            stu_answer: '', // 学生作答
            score: 0, // 分数
            right_flag: 0,
            sort_index: item.sort_index // 题目对应的排序号
          }
        })
        this.toggleTopic(0)
        // 计时开始
        let time = 0
        clearInterval(this.setTime)
        this.setTime = setInterval(() => {
          time++
          if (time < 60) {
            this.timing = time < 10 ? '00:0' + time : '00:' + time
          } else if (time < 3600) {
            this.timing = Math.floor(time / 60) < 10 ? '0' + Math.floor(time / 60) + ':' + (time % 60 < 10 ? '0' + time % 60 : time % 60) : Math.floor(time / 60) + ':' + (time % 60 < 10 ? '0' + time % 60 : time % 60)
          } else {
            this.$alert('答题超时，确定后将自动提交', '超时', {
              confirmButtonText: '确定'
            })
            clearInterval(this.setTime)
          }
        }, 1000)
        // 计时end
      }
    },
    async updateTestDuration () {
      const res = await updateTestDuration({ stuOnlineLessonTestId: this.info.stuOnlineLessonTestId })
      if (res.code !== '200') {
        this.$message.error(res.message)
      }
    },
    async testSubmit (data) {
      this.btnDisabled = true
      const res = await testSubmit(data)
      if (res.code === '200') {
        this.$message.success('提交成功')
        // 重新刷新活动列表
        this.$emit('handleEmit', 'confirm')
      } else {
        this.$message.error(res.message)
        this.btnDisabled = false
      }
    },
    inputSheet (item) { // 填空题录入
      this.sheet[this.currentTopicIndex].stu_answer = item.map(el => el.stu_answer).filter(el => el).length > 0 ? item.map(el => el.stu_answer).join(',') : ''
      this.sheet[this.currentTopicIndex].right_flag = this.sheet[this.currentTopicIndex].stu_answer === this.subjectList[this.currentTopicIndex].right_answer_list.map(el => el.right_answer).join(',') ? 1 : 0
    },
    choiceSheet (item) { // 选择题选入
      if (this.topic.subject_type === '13') {
        return
      }
      if (this.topic.subject_type === '11') {
        item.checked = !item.checked
        this.sheet[this.currentTopicIndex].stu_answer = this.topic.options.filter(el => {
          return el.checked
        }).map(el => {
          return el.num
        }).join(',')
        this.sheet[this.currentTopicIndex].right_flag = item.right_answer === this.sheet[this.currentTopicIndex].stu_answer ? 1 : 0
      } else if (this.topic.subject_type === '12') {
        this.topic.options.forEach(el => {
          if (item.num !== el.num) {
            el.checked = false
          } else {
            item.checked = true
          }
        })
        this.sheet[this.currentTopicIndex].right_flag = item.right_answer === item.num ? 1 : 0
        this.sheet[this.currentTopicIndex].stu_answer = item.num
      } else {
        this.sheet[this.currentTopicIndex].right_flag = item.right_answer === item.num ? 1 : 0
        this.sheet[this.currentTopicIndex].stu_answer = item.num
      }
    },
    // 切换题目
    toggleTopic (index) {
      this.currentTopicIndex = index
      this.topic.display_type = this.subjectList[index].display_type
      this.topic.file_url = this.subjectList[index].file_url || ''
      this.topic.sort_index = this.subjectList[index].sort_index
      this.topic.subject_id = this.subjectList[index].subject_id
      this.topic.subject_type = this.subjectList[index].subject_type
      this.topic.subject_content = this.subjectList[index].subject_content
      this.topic.itemList = this.subjectList[index].itemList
      if (this.topic.subject_type === '13') { // 填空题只根据括号‘（’来识别，若接口出现其他形式的数据则失效，此时改接口返回数据或者增加js功能
        this.topic.options = []
        for (let i = 1; i < this.subjectList[index].right_answer_list.length + 1; i++) {
          let answer = this.sheet[this.currentTopicIndex].stu_answer.split(',')
          this.topic.options.push({
            stu_answer: answer[i - 1] || '',
            right_answer: this.subjectList[index].right_answer,
            num: i
          })
        }
      } else if (this.topic.subject_type === '10' || this.topic.subject_type === '11') {
        this.topic.options = this.topic.itemList.map(el => {
          return {
            num: el.answer_code,
            stu_answer: el.resource_subject_item_tent,
            right_answer: this.subjectList[index].right_answer,
            checked: false
          }
        })
        if (this.topic.subject_type === '11') {
          this.topic.options = this.topic.options.map(el => {
            el.checked = this.sheet[this.currentTopicIndex].stu_answer.indexOf(el.num) > -1
            return el
          })
        }
      } else if (this.topic.subject_type === '12') {
        this.topic.options = this.topic.itemList.map((el, i) => {
          return {
            num: ['A', 'B'][i],
            stu_answer: el.resource_subject_item_tent,
            right_answer: this.subjectList[index].right_answer,
            checked: this.sheet[this.currentTopicIndex].stu_answer === el.resource_subject_item_tent
          }
        })
      } else {
        this.topic.options = [
          { stu_answer: this.sheet[this.currentTopicIndex].stu_answer || '', right_answer: this.subjectList[index].right_answer }
        ]
      }
    },
    // 点击按钮切换题目
    jumpPage (state) {
      this.currentTopicIndex += state
      this.toggleTopic(this.currentTopicIndex)
    },
    // 提交测验
    submitForm () {
      let score = 0
      let unAnswer = this.sheet.filter(el => {
        score += el.score
        return el.stu_answer === ''
      })
      let alertMsg = unAnswer.length !== 0 ? '您还有题目未完成是否确定提交？' : '确定提交本次测验？'
      this.$confirm(alertMsg, '提交', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        const data = {
          id: this.info.stuOnlineLessonTestId,
          resultJson: JSON.stringify(this.sheet),
          score
        }
        this.testSubmit(data)
      })
    },
    closeBox () {
      this.$emit('handleEmit')
    }
  },
  mounted () {
    this.testMain()
    this.timer = setInterval(() => {
      this.updateTestDuration()
    }, 8000)
  },
  beforeDestroy () {
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style scoped lang="scss" rel="stylesheet/scss">
  .question-title {
    margin: 40px 0 30px;font-size: 16px;color: #101d37;line-height: 2;white-space:pre-wrap
  }
  .item {
    display: flex;border-radius: 3px;align-items: center;margin-bottom: 20px;font-size: 16px;line-height: 2;padding: 0 20px;
    .question-content {
      margin-left: 10px;font-size: 16px;
      input{
        height: 36px;padding: 0 10px;border: none;border-bottom: solid 1px #91959a;outline: none;
      }
    }
    // 右侧的按钮
    .chooseBtn {
      color: #101d37;width: 36px;height: 36px;background: #fff;text-align: center;line-height: 38px;border-bottom: 1px solid #91959a;display: block;
    }
    textarea{
      width: 100%;padding: 10px;line-height: 1.75;outline: none;font-size: 16px;border-radius: 3px;border:solid 1px #91959a; resize:none;
    }
  }
  .item:hover {
    background: #EBEEF5
  }
  .item.active {
    background: #72B6FF;color: #fff
  }
  .item.active .chooseBtn{
    border-color: #72B6FF;color: #72B6FF;
  }
  .item.active .question-content input{
    border-color: #72B6FF;color: #72B6FF;
  }
  // 底部控制按钮
  .controller {
    display: flex;padding: 10px 0;width: 100%;justify-content: space-between;
  }
</style>
